package com.zhs.xyzsdk.wizards;

import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

import com.zhs.xyzsdk.builder.XYZNature;

public class NewProjectWizard extends Wizard implements INewWizard {

	public NewProjectWizard() {
		setNeedsProgressMonitor(true);
	}

	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}

	public void addPages() {
		page = new NewProjectWizardPage(selection);
		addPage(page);
	}

	public boolean performFinish() {
		final String varName = page.getClasspathVariable();
		final String projName = page.getProjectName();
		try {
			getContainer().run(true, false, new WorkspaceModifyOperation() {

				protected void execute(IProgressMonitor monitor)
						throws CoreException, InvocationTargetException,
						InterruptedException {
					doFinish(varName, projName, monitor);
				}

			});
		} catch (InterruptedException _ex) {
			return false;
		} catch (InvocationTargetException e) {
			// Throwable realException = e.getTargetException();
			return false;
		}
		return true;
	}

	private void doFinish(String varName, String projName,
			IProgressMonitor monitor) throws CoreException {
		monitor.beginTask("Creating XYZ Project", 3);
		IProject proj = createProject(projName, new SubProgressMonitor(monitor,
				1));
		proj.open(new SubProgressMonitor(monitor, 1));
		init(proj, new SubProgressMonitor(monitor, 1));
		monitor.done();
	}

	private IProject createProject(String name, IProgressMonitor monitor)
			throws CoreException {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		IProjectDescription description = workspace.newProjectDescription(name);
		description.setNatureIds(new String[] { XYZNature.NATURE_ID });
		IProject proj = workspace.getRoot().getProject(name);
		proj.create(description, monitor);
		return proj;
	}

	private void init(IProject proj, SubProgressMonitor monitor)
			throws CoreException {
		monitor.beginTask("Adding Nature", 4);
		IFolder srcDir = proj.getFolder("src");
		IFolder binDir = proj.getFolder("bin");
		if (!srcDir.exists())
			srcDir.create(false, true, new SubProgressMonitor(monitor, 1));
		if (!binDir.exists())
			binDir.create(false, true, new SubProgressMonitor(monitor, 1));
		proj.getNature(XYZNature.NATURE_ID).configure();
	}
	private NewProjectWizardPage page;
	private ISelection selection;

}